package com.ybc.chinese.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.Gravity;
import android.widget.Toast;

import java.util.Collection;

/**
 * <p>常用工具类<p/>
 * Created by Yubch on 17/2/15.
 */
public class CommonUtil {

    /**
     * 判断是否有网络连接
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 提示toast
     *
     * @param context      上下文环境
     * @param resId        提示内容的资源id
     * @param isShortToast 是不是短提示，可选填
     */
    public static void showToast(Context context, int resId, boolean... isShortToast) {
        int during;
        if (isShortToast.length > 0 && isShortToast[0]) {
            during = Toast.LENGTH_SHORT;
        } else {
            during = Toast.LENGTH_LONG;
        }
        Toast toast = Toast.makeText(context, resId, during);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    /**
     * 提示toast
     *
     * @param context      上下文环境
     * @param s            提示内容
     * @param isShortToast 是不是短提示，可选填
     */
    public static void showToast(Context context, String s, boolean... isShortToast) {
        int during;
        if (isShortToast.length > 0 && isShortToast[0]) {
            during = Toast.LENGTH_SHORT;
        } else {
            during = Toast.LENGTH_LONG;
        }
        Toast.makeText(context, s, during).show();
    }

    /**
     * 返回当前程序的版本名称
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        PackageInfo packInfo = null;
        try {
            packInfo = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return packInfo.versionName;
    }

    /**
     * 判断数组是否为空
     *
     * @param data
     * @return
     */
    public static boolean isEmpty(Collection data) {
        return data == null || data.size() == 0;
    }

    /**
     * 判断数组是否为空
     *
     * @param data
     * @return
     */
    public static boolean isEmpty(Object[] data) {
        return data == null || data.length == 0;
    }
}
